import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutterapp/src/page/home/list_item2_widget.dart';
import 'package:flutterapp/src/page/home/list_item_widget.dart';
import 'package:flutterapp/src/utils/log_utils.dart';
import 'package:video_player/video_player.dart';

class HomeItemPage extends StatefulWidget {
  final int flag;
  HomeItemPage(this.flag);
  @override
  _HomeItemPageState createState() => _HomeItemPageState();
}

class _HomeItemPageState extends State<HomeItemPage> {
  // 创建一个多订阅流
  StreamController<VideoPlayerController> _streamController =
      StreamController.broadcast();

  VideoPlayerController _videoPlayerController;
  bool _isScroll = false;

  @override
  void initState() {
    super.initState();
    // 创建一个消息监听 来自其他页面的监听
    _streamController.stream.listen((event) {
      // 接受消息
      LogUtils.e("接受消息 $event");
      if (_videoPlayerController != null &&
          _videoPlayerController.textureId != event.textureId) {
        _videoPlayerController.pause();
      }
      _videoPlayerController = event;
    });
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("视频列表"),
        ),
        backgroundColor: Colors.white,
        body: NotificationListener(
          onNotification: (ScrollNotification notification) {
            Type runtimeType = notification.runtimeType;
            if (runtimeType == ScrollStartNotification) {
              LogUtils.e("开始滑动");
              _isScroll = true;
            } else {
              LogUtils.e("滑动结束");
              _isScroll = false;
            }
            setState(() {});

            return false;
          },
          child: ListView.builder(
              itemCount: 50,
              cacheExtent: 0, // 缓存距离0
              itemBuilder: (BuildContext context, int index) {
                return buildListItemFunction();
              }),
        ));
  }

  Widget buildListItemFunction() {
    if (widget.flag == 1) {
      return ListItemWidget(
          streamController: _streamController, isScroll: _isScroll);
    } else {
      return ListItem2Widget(
          streamController: _streamController, isScroll: _isScroll);
    }
  }
}
